package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.mapper.DyOrderMapper;
import com.settlement.system.model.entity.DyOrder;
import com.settlement.system.model.entity.SysPlatform;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.query.DyOrderPageQuery;
import com.settlement.system.model.vo.DyOrderImportVo;
import com.settlement.system.service.DyOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 抖音订单 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-05
 */
@Service
@RequiredArgsConstructor
public class DyOrderServiceImpl extends ServiceImpl<DyOrderMapper, DyOrder> implements DyOrderService {

    @Override
    public Page<DyOrder> getDyOrderPage(DyOrderPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        String tableName = "dy_order_%s".formatted(queryParams.getBillMonth());
        queryParams.setTableName(tableName);
        if (!StringUtils.hasText(this.baseMapper.existTable(tableName))) {
            return new Page<>(pageNum, pageSize);
        }
        Page<DyOrder> page = new Page<>(pageNum, pageSize);
        return this.baseMapper.getPage(page, queryParams);
    }

    @Override
    public List<DyOrder> getList(DyOrderPageQuery queryParams) {
        // 根据账单日期查询对应表的核销数据
        return this.baseMapper.getList(queryParams);
    }

    @Override
    public void addImportData(List<DyOrderImportVo> vos, SysStore sysStore, SysPlatform sysPlatform, Map<String, String> linkNoMap) {
        List<String> billMonthList = new ArrayList<>();
        for (DyOrderImportVo vo : vos) {
            if (vo.getOrderTime() != null) {
                String billMonth = DateUtils.formatDate(vo.getOrderTime());
                if (!billMonthList.contains(billMonth)) {
                    billMonthList.add(billMonth);
                }
            }
        }
        List<String> subOrderNos =
                vos.stream().map(DyOrderImportVo::getSubOrderNo).filter(StringUtils::hasText).toList();
        // 所有存在的记录
        List<DyOrder> list = new ArrayList<>();
        for (String billMonth : billMonthList) {
            DyOrderPageQuery pageQuery = new DyOrderPageQuery();
            pageQuery.setSubOrderNos(subOrderNos);
            pageQuery.setTableName("dy_order_%s".formatted(billMonth));
            // 根据账单日期查询对应表的核销数据
            List<DyOrder> dyOrderList = new ArrayList<>();
            if (StringUtils.hasText(this.baseMapper.existTable(pageQuery.getTableName()))) {
                dyOrderList = this.baseMapper.getList(pageQuery);
            }
            if (dyOrderList != null && dyOrderList.size() > 0) {
                list.addAll(dyOrderList);
            }
        }
        // 需要新建的列表
        List<DyOrderImportVo> createVos = new ArrayList<>();
        // 需要更新的列表
        List<DyOrderImportVo> updateVos = new ArrayList<>();
        for (DyOrderImportVo vo : vos) {
            DyOrder record = list.stream()
                    .filter(dyOrder -> dyOrder.getSubOrderNo().equals(vo.getSubOrderNo()))
                    .findFirst().orElse(null);
            if (record == null) {
                // 加入到新建列表
                createVos.add(vo);
            } else {
                // 加入到更新列表
                updateVos.add(vo);
            }
        }
        for (DyOrderImportVo updateVo : updateVos) {
            // 更新操作
            list.stream().filter(dyOrder -> dyOrder.getSubOrderNo().equals(updateVo.getSubOrderNo())).findFirst().ifPresent(dyOrder -> {
                BeanUtil.copyProperties(updateVo, dyOrder, "id", "orderTime", "orderFinishTime", "payFinishTime", "promiseSendTime", "previousSendTime", "sendTime", "previousReceiveTime", "storeId");
                dyOrder.setOrderTime(updateVo.getOrderTime());
                dyOrder.setOrderFinishTime(DateUtils.convert(updateVo.getOrderFinishTime()));
                dyOrder.setPayFinishTime(DateUtils.convert(updateVo.getPayFinishTime()));
                dyOrder.setPromiseSendTime(DateUtils.convert(updateVo.getPromiseSendTime()));
                dyOrder.setPreviousSendTime(DateUtils.convert(updateVo.getPreviousSendTime()));
                dyOrder.setSendTime(DateUtils.convert(updateVo.getSendTime()));
                dyOrder.setPreviousReceiveTime(DateUtils.convert(updateVo.getPreviousReceiveTime()));
                dyOrder.setTableName("dy_order_%s".formatted(DateUtils.formatDate(dyOrder.getOrderTime())));
                this.baseMapper.update(dyOrder);
            });
        }
        for (DyOrderImportVo vo : createVos) {
            DyOrder dyOrder = new DyOrder();
            BeanUtil.copyProperties(vo, dyOrder, "orderTime", "orderFinishTime", "payFinishTime", "promiseSendTime", "previousSendTime", "sendTime", "previousReceiveTime", "storeId");
            dyOrder.setOrderTime(vo.getOrderTime());
            dyOrder.setOrderFinishTime(DateUtils.convert(vo.getOrderFinishTime()));
            dyOrder.setPayFinishTime(DateUtils.convert(vo.getPayFinishTime()));
            dyOrder.setPromiseSendTime(DateUtils.convert(vo.getPromiseSendTime()));
            dyOrder.setPreviousSendTime(DateUtils.convert(vo.getPreviousSendTime()));
            dyOrder.setSendTime(DateUtils.convert(vo.getSendTime()));
            dyOrder.setPreviousReceiveTime(DateUtils.convert(vo.getPreviousReceiveTime()));
            dyOrder.setTableName("dy_order_%s".formatted(DateUtils.formatDate(dyOrder.getOrderTime())));
            dyOrder.setPlatform(sysPlatform.getPlatformKey());
            dyOrder.setStoreId(sysStore.getId());
            dyOrder.setStoreName(sysStore.getCommercePlatformStoreName());
            dyOrder.setAuditNo(linkNoMap.get(vo.getSubOrderNo()));
            dyOrder.setBillMonth(linkNoMap.get(vo.getSubOrderNo() + "账单月份"));
            // 判断历史表是否存在，不存在则新增
            if (!StringUtils.hasText(this.baseMapper.existTable(dyOrder.getTableName()))) {
                this.createTable(dyOrder.getTableName());
            }
            this.baseMapper.insertData(dyOrder);
        }
    }

    @Override
    public boolean createTable(String tableName) {
        return this.getBaseMapper().createTable(tableName) > 0;
    }
}
